jQuery(document).ready(function() {
	
	//baseurl="http://goplay.globe.com.ph/tiangge/index.php/";		
	resizeIframe();

	jQuery(window).on("resize", function(event){
		resizeIframe();
	});
	
	var current_pos = getCookie("tiangge_current_pos");
	var base_url = baseurl + "promo/";
	
	if (current_pos > 0) {
		//alert(current_pos + "TRUE");
		if(current_pos=="1") {
		jQuery("div.wizard a:nth-of-type(1)").attr("class","current done");
		jQuery("div.wizard a:nth-of-type(2)").attr("class","current");
		jQuery("div.wizard a:nth-of-type(3), div.wizard a:nth-of-type(4), div.wizard a:nth-of-type(5)").removeAttr("href");
		}
		if(current_pos=="2") {
		jQuery("div.wizard a:nth-of-type(1), div.wizard a:nth-of-type(2)").attr("class","current done");
		jQuery("div.wizard a:nth-of-type(3)").attr("class","current");
		jQuery("div.wizard a:nth-of-type(4), div.wizard a:nth-of-type(5)").removeAttr("href");
		
		  var mode = getCookie("tiangge_mode");
		  var promo = getCookieR("tiangge_promo");
		  var promoDesc = getCookieR("tiangge_promoDesc");
		  var commitmentBox = getCookieR("tiangge_commitmentBox");
		  
          if(mode!="edit"){      
			jQuery(".promoBox, .commitmentBox").addClass("active");
			jQuery('#pname, #pemail, #pdob, #padd').hide();
			if (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0) {
				promoDesc = promoDesc.replace("john", ",");
				promoDesc = promoDesc.replace("john ", ", ");
				jQuery('#promo').html(promo + promoDesc);
			} else {
				jQuery('#promo').html(promo + promoDesc);
			}
			jQuery('#commitmentBox').text(commitmentBox);
		  }
		}
		if(current_pos=="3") {
		jQuery("div.wizard a:nth-of-type(1), div.wizard a:nth-of-type(2),div.wizard a:nth-of-type(3)").attr("class","current done");
		jQuery("div.wizard a:nth-of-type(4)").attr("class","current");
		jQuery("div.wizard a:nth-of-type(5)").removeAttr("href");
		
		  var mode = getCookie("tiangge_mode");
		  var promo = getCookieR("tiangge_promo");
		  var promoDesc = getCookieR("tiangge_promoDesc");
		  var commitmentBox = getCookieR("tiangge_commitmentBox");
		  var mobtel = getCookieR("tiangge_mobtel");
		  if(mobtel=="0"){jQuery('#mobtel').text("None");} else {jQuery('#mobtel').text(mobtel);}
          if(mode!="edit"){      
			jQuery(".promoBox, .commitmentBox, .prepaidBox").addClass("active");
			jQuery('#pname, #pemail, #pdob, #padd').hide();
			if (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0) {
				promoDesc = promoDesc.replace("john", ",");
				promoDesc = promoDesc.replace("john ", ", ");
				jQuery('#promo').html(promo + promoDesc);
			} else {
				jQuery('#promo').html(promo + promoDesc);
			}
			jQuery('#commitmentBox').text(commitmentBox);
			if(mobtel=="0"){jQuery('#mobtel').text("None");} else {jQuery('#mobtel').text(mobtel);}
		  }
		}
		if(current_pos=="4" || current_pos=="5") {
		jQuery("div.wizard a:nth-of-type(1),div.wizard a:nth-of-type(2),div.wizard a:nth-of-type(3),div.wizard a:nth-of-type(4)").attr("class","current done");
		jQuery("div.wizard a:nth-of-type(5)").attr("class","width100 current");
		
		  var mode = getCookie("tiangge_mode");
		  var promo = getCookieR("tiangge_promo");
		  var promoDesc = getCookieR("tiangge_promoDesc");
		  var commitmentBox = getCookieR("tiangge_commitmentBox");
		  var mobtel = getCookieR("tiangge_mobtel");
		  var username = getCookieR("tiangge_username");
		  var eadd = getCookieR("tiangge_eadd");
		  var bday = getCookieR("tiangge_bday");
		  var address = getCookieR("tiangge_address");
		  if(mobtel=="0"){jQuery('#mobtel').text("None");} else {jQuery('#mobtel').text(mobtel);}
          if(mode!="edit"){ 
			jQuery(".promoBox, .commitmentBox, .prepaidBox, .profileBox").addClass("active");
			jQuery(".pnone").hide();
			if (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0) {
				promoDesc = promoDesc.replace("john", ",");
				promoDesc = promoDesc.replace("john ", ", ");
				jQuery('#promo').html(promo + promoDesc);
			} else {
				jQuery('#promo').html(promo + promoDesc);
			}
			jQuery('#commitmentBox').text(commitmentBox);
			if(mobtel=="0"){jQuery('#mobtel').text("None");} else {jQuery('#mobtel').text(mobtel);}
			jQuery('#name').text(username);
			jQuery('#email').text(eadd);
			jQuery('#dob').text(bday);
			jQuery('#add').text(address);
			jQuery("#pname, #pemail, #pdob, #padd").show();
		  }
		}
	} else {
		//alert(current_pos + "FALSE");
		jQuery("div.wizard a:nth-of-type(1), div.wizard a:nth-of-type(2), div.wizard a:nth-of-type(3), div.wizard a:nth-of-type(4), div.wizard a:nth-of-type(5)").removeAttr("href");
	} 
	if (current_pos > 1) {
		//var promo_id = getCookie("tiangge_promoTypeid");
		var id = getCookie('tiangge_id');
		var ids = id.split(".");
		var promo_id = ids[0];
		
		/* if(jQuery("#promoType-inner .active").children('h5').html()=='ALLNET TEXTS') { 
			var name = 'ALLNET TEXTS'; 
			//console.log(name);
		} else {
			var name = 'UNLI CALLS';
			//console.log(name);
		} */
		var name = jQuery("#promoType-inner .selectPromoLowerText1.active").html();
		var validity = getCookie("tiangge_validity");
		//var promoTypeid = getCookie('tiangge_promoid');
		//var gadgetplanprice = getCookie('tiangge_planprice');
		var gadgetplanprice = '3000.00';
		
		var id = getCookie('tiangge_id');
		var ids = id.split(".");
		var promoTypeid = ids[1];

		populateValidity(promo_id);
		populatePromoDetails(promo_id,name,validity);
		populateCommitmentPeriod(promoTypeid,gadgetplanprice);
		
		jQuery("#validity, #choosePromo, #commitment").show();
	} else{
		jQuery("#validity, #choosePromo, #commitment, #promoConfirm").hide();
	}
	
/* . . . . . . . . . . . . . . . Ajax Promo . . . . . . . . . . . . . . . . . . */

	if (/promo/.test(self.location.href)){
		
		jQuery.getJSON(base_url+"getpromotypelist",{ajax:'true'},function(j){
			var ht = '';
			//j.reverse(sort_by('promoTypeId', true, parseInt));
			j.sort(sort_by('promoTypeId', true, parseInt));
			for(var i=0;i<j.length;i++){
			   //var codeLine = j[i].promoTypeName;
			   //var firstWord = codeLine.substr(0, codeLine.indexOf(" "));
			   //ht+='<a href="#." class="selectPromo inBlock"><span style="display:none;" id="promoTypeid" >'+j[i].promoTypeId+'</span><span id= "img_icon" class="promoIcons1 floatLeft"></span><p class="floatLeft">'+j[i].promoTypeDescription+'</p><h5 class="clear">'+j[i].promoTypeName+'</h5></a>';
				ht+='<div class="selectPromo"><div class="selectPromoUpper"><div style="display:none;" value="'+j[i].promoTypeId+'" id="promoTypeid">'+j[i].promoTypeId+'</div><div class="selectPromoIcon1"></div><div class="selectPromoTextUpper">'+j[i].promoTypeDescription+'</div><div class="clear"></div></div><div class="selectPromoLower"><div class="selectPromoLowerText1">'+j[i].promoTypeName+'</div><div class="selectPromoLowerText2"></div></div></div>';
			}
				ht+='<div class="clear"></div>';
				jQuery("#promoType-inner").html(ht);
				jQuery("div#promoType-inner a:nth-of-type(2) span#img_icon").attr("class","promoIcons2 floatLeft");		

				if (current_pos > 1) {
					//var promoTypeid = getCookie("tiangge_promoTypeid");
					var id = getCookie('tiangge_id');
					var ids = id.split(".");
					var promoTypeid = ids[0];
					jQuery("#promoType-inner #promoTypeid:contains("+promoTypeid+")").addClass("active");
					jQuery('#promoType-inner .selectPromo').filter(function(){
						return $(this).has('.active').length > 0
					}).each(function(){
						jQuery(".selectPromoUpper, .selectPromoLowerText1, .selectPromoLowerText2", this).addClass('active');
						jQuery(this).addClass("active");
					});
				}
				resizeIframe();
		});		
	}		
	
	/*Choose Promo Type*/
	jQuery('#promoType-inner').on("click", ".selectPromo", function () {
		var $this = $(this);
	   	$this.siblings().removeClass('active');
	   	jQuery(".selectPromoUpper, .selectPromoLowerText1, .selectPromoLowerText2").removeClass('active');
	   	if ($this.hasClass('active')) {
	   	    jQuery(".selectPromoUpper, .selectPromoLowerText1, .selectPromoLowerText2", this).removeClass('active');
	      	$this.removeClass('active');
			jQuery("#validity, #choosePromo, #commitment, #promoConfirm").hide();
			jQuery("#commitment a, #choosePromo a, #validity a, .promoBox, .commitmentBox").removeClass('active');
			jQuery("p#promo, p#commitmentBox").html("None");
			resizeIframe();
			return false;
	   	} else {
	      	$this.addClass('active');
	      	jQuery(".selectPromoUpper, .selectPromoLowerText1, .selectPromoLowerText2", this).addClass('active');
			jQuery("#validity, #choosePromo, #commitment, #promoConfirm").hide();
			jQuery("#validity a, #choosePromo a, #commitment a").removeClass('active');
			jQuery("p#promo, p#commitmentBox").html("None");
			jQuery(".promoBox, .commitmentBox").removeClass('active');
			var promo_id = jQuery("#promoType-inner .selectPromoUpper.active #promoTypeid").attr('value');
			
			//setCookie("tiangge_promoTypeid",promo_id);
			var id = getCookie('tiangge_id');
			if(id==""){
				var id = promo_id + "...";
				setCookie("tiangge_id",id);
			}
			else{
		        var id = getCookie('tiangge_id');
				var idArray = [];
				var id = id.split(".");
				var i = 0;					
				jQuery.each(id , function(index, value){
					if (i==0) value=promo_id;
					idArray.push(value);
					i++;
				});
									 
				id = idArray.join(".");
				setCookie("tiangge_id",id);
				//console.log("promotypeid."  + id);
			}
			jQuery.getJSON(base_url+"getpromovaliditylist/"+promo_id,{ajax:'true'},function(j){
				j.sort(sort_by('validity', true, parseInt));
				var ht = '';
				for(var i=0;i<j.length;i++){
					if(j[i].validity=='1') day='day'; else day='days';
					//ht+='<a href="#." class="selectValidity inBlock margRight5"><h5 id="numofdays">'+j[i].validity+'</h5><p>'+j[i].validity+' '+day+'</p></a>';
					ht+='<div class="selectValidity"><div class="selectValiditydynamicUpper"><div class="selectValidityUpperText">'+j[i].validity+'</div></div><div class="selectValiditydynamicLower"><div class="selectValiditydynamicLower1">'+j[i].validity+' '+day+'</div><div class="selectValiditydynamicLower2"></div></div></div>';
				}
				ht+='<div class="clear"></div>';
				jQuery("div#validity").show();
				jQuery("#validity-inner").html(ht);
				resizeIframe();
				if ("window", $( window ).width() < 361) {
					scrollFrameHeight('730');
				} else  if ("window", $( window ).width() < 641) {
					scrollFrameHeight('750');
				} else {
					scrollFrameHeight('300');
				}
				 
			});
		}
	});
	
	/*Choose Validity Period*/
	jQuery('#validity-inner').on("click", ".selectValidity", function () {
		var $this = $(this);
	   	$this.siblings().removeClass('active');
		jQuery(".selectValiditydynamicUpper, .selectValiditydynamicLower1, .selectValiditydynamicLower2").removeClass('active');
	   	if ($this.hasClass('active')) {
			jQuery(".selectValiditydynamicUpper, .selectValiditydynamicLower1, .selectValiditydynamicLower2", this).removeClass('active');
	      	$this.removeClass('active');
			jQuery("#choosePromo, #commitment, #promoConfirm").hide(); 
			jQuery("#choosePromo a, #commitment a, .promoBox, .commitmentBox").removeClass('active');
			jQuery("p#promo").html("None");
			jQuery("p#commitmentBox").html("None");
			resizeIframe();
			return false;
	   	} else {
	      	$this.addClass('active');
			jQuery(".selectValiditydynamicUpper, .selectValiditydynamicLower1, .selectValiditydynamicLower2", this).addClass('active');
			jQuery("#choosePromo, #commitment, #promoConfirm").hide();
			jQuery("#choosePromo a, #commitment a").removeClass('active');
			var promo_id = jQuery("#promoType-inner .selectPromoUpper.active #promoTypeid").attr('value');
			
			/* if(jQuery("#promoType-inner .active").children('h5').html()=='ALLNET TEXTS') { 
				var name = 'ALLNET TEXTS'; 
				//console.log(name);
			} else {
				var name = 'UNLI CALLS';
				//console.log(name);
			} */
				var name = jQuery("#promoType-inner .selectPromoLowerText1.active").html();
				var validity = jQuery("#validity-inner .selectValiditydynamicUpper.active .selectValidityUpperText").html();
				
			jQuery.getJSON(base_url+"getpromolist/"+promo_id+"/"+name+"/"+validity,{ajax:'true'},function(j){
				j.sort(sort_by('promoPrice', true, parseInt));
				var ht = '';
				for(var i=0;i<j.length;i++){
				  if(j[i].promoTextDesc=="unli allnet texts" || j[i].promoTextDesc=="unlimited texts to all networks") { 
					var promoTextDesc = "Unli to all networks"; 
				  } else {
					var promoTextDesc = j[i].promoTextDesc;
					promoTextDesc = promoTextDesc.replace(" to Globe/TM", "");
					promoTextDesc = promoTextDesc + "*";
				  }
				  if(j[i].promoCallDesc=="unli calls to Globe/TM") {
					var promoCallDesc = ConvertFirstCharacterToUpperCase(j[i].promoCallDesc);
					promoCallDesc = promoCallDesc.replace(" to Globe/TM", "");
					promoCallDesc = promoCallDesc + "*";
				  } else {
					  var promoCallDesc = j[i].promoCallDesc;
					  if (/minutes/.test(promoCallDesc)) { promoCallDesc = promoCallDesc.replace(" of calls to Globe/TM", "") + "*"; }
					  if (/mins of calls to Globe/.test(promoCallDesc)){ promoCallDesc = promoCallDesc.replace("mins of calls to Globe/TM", "") + "minutes*"; }
					  if (/mins of Globe/.test(promoCallDesc)) { promoCallDesc = promoCallDesc.replace("mins of Globe/TM calls", "") + "minutes*"; }
					  if (/null/.test(promoCallDesc) || promoCallDesc==="") { /*promoCallDesc = "None";*/ promoCallDesc = "0 minutes";	}
				  }
				  var promoSurfDesc = j[i].promoSurfDesc;
				  var promoPrice = j[i].promoPrice;
				  promoSurfDesc = promoSurfDesc.replace(" data", "");
				  promoPrice = promoPrice + "0";
				  var promoDesc = j[i].promoDesc;
				  
				  //ht+='<a href="#." class="choosePromo"><span style="display:none;" class="'+j[i].promoPrice+'" id="promolistid" >'+j[i].promoId+'</span><span style="display:none;" id="promoDesc" >'+promoDesc+'</span><ul><li><span class="choosePromoIcon one"></span>'+promoTextDesc+'</li><li><span class="choosePromoIcon two"></span>'+promoCallDesc+'</li><li><span class="choosePromoIcon three"></span>'+promoSurfDesc+'</li><li><span class="choosePromoIcon four"></span>P'+promoPrice+'</li></ul><h5>'+j[i].promoName+'</h5></a>';
				  ht+='<div class="choosePromo"><span style="display:none;" class="'+j[i].promoPrice+'" id="promolistid" >'+j[i].promoId+'</span><span style="display:none;" id="promoDesc" >'+promoDesc+'</span><div class="choosePromodynamicUpper"><div class="rowcont"><div class="rowcontlogo image1"></div><div class="rowconttext">'+promoTextDesc+'</div><div class="clear"></div></div><div class="rowcont"><div class="rowcontlogo image2"></div><div class="rowconttext">'+promoCallDesc+'</div><div class="clear"></div></div><div class="rowcont"><div class="rowcontlogo image3"></div><div class="rowconttext">'+promoSurfDesc+'</div><div class="clear"></div></div><div class="rowcont"><div class="rowcontlogo image4"></div><div class="rowconttext">P'+promoPrice+'</div><div class="clear"></div></div><div class="clear"></div></div><div class="choosePromodynamicLower"><div class="choosePromodynamicLowerText1">'+j[i].promoName+'</div><div class="choosePromodynamicLowerText2"></div></div></div>';
				}
				
				ht+='<div class="clear"></div>';
				jQuery("#choosePromo").show();
				jQuery("#choosePromo-inner").html(ht); 
				
			 	var maxHeight = -1;
				jQuery('.choosePromodynamicUpper').each(function() {
				  maxHeight = maxHeight > jQuery(this).height() ? maxHeight : jQuery(this).height();
				});

				jQuery('.choosePromodynamicUpper').each(function() {
				  jQuery(this).height(maxHeight);
				});
				
				resizeIframe();

				if ("window", $( window ).width() < 361) {
					scrollFrameHeight('1280');
				} else if ("window", $( window ).width() < 641) {
					scrollFrameHeight('1300');
				} else {
					scrollFrameHeight('600');
				}

			
				}); 
	  	}
	});
	
	/*Choose Promo Details*/
	jQuery('#choosePromo-inner').on("click", ".choosePromo", function () {
		var $this = $(this);
	   	$this.siblings().removeClass('active');
	   	jQuery(".choosePromodynamicUpper, .choosePromodynamicLowerText1, .choosePromodynamicLowerText2").removeClass('active');
	   	if ($this.hasClass('active')) {
	      	$this.removeClass('active');
	      	jQuery(".choosePromodynamicUpper, .choosePromodynamicLowerText1, .choosePromodynamicLowerText2", this).removeClass('active');
	     	jQuery("#commitment, #promoConfirm").hide();
			jQuery("#commitment a, .promoBox, .commitmentBox").removeClass('active');
			jQuery("p#promo, p#commitmentBox").html("None");
			resizeIframe();
			return false;
	   	} else {
	      	$this.addClass('active');
	      	jQuery(".choosePromodynamicUpper, .choosePromodynamicLowerText1, .choosePromodynamicLowerText2", this).addClass('active');
			var $validity = jQuery("#validity-inner .selectValiditydynamicLower1.active").html();
			var $promo = jQuery('#choosePromo-inner .choosePromodynamicLowerText1.active').text(); 
			
			if (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0) {
				var promoDesc = jQuery("#choosePromo-inner .active").children('span#promoDesc').text();
				promoDesc = ConvertFirstCharacterToUpperCase(promoDesc);
				jQuery("p#promo").html($validity + ' - ' + $promo + '<br><br>' + promoDesc);
				promoDesc = promoDesc.replace(",", "john");
				promoDesc = promoDesc.replace(", ", "john ");
				setCookie("tiangge_promoDesc",promoDesc);
				//console.log(promoDesc + " " + getCookieR("tiangge_promoDesc"));
			} else {
				var promoDesc = jQuery("#choosePromo-inner .active").children('span#promoDesc').text();
				promoDesc = ConvertFirstCharacterToUpperCase(promoDesc);
				setCookie("tiangge_promoDesc",promoDesc);
				jQuery("p#promo").html($validity + ' - ' + $promo + '<br><br>' + promoDesc);
			}
		
			jQuery("#commitment, #promoConfirm").hide();
			jQuery(".promoBox").addClass("active");
			jQuery("#commitment a").removeClass('active');
			
			var promo = $validity + ' - ' + $promo + '<br><br>';
			setCookie("tiangge_promo",promo);
						
			var promolist_id=jQuery("#choosePromo-inner .active").children('span').html();
			//console.log(promolist_id);
			//setCookie("tiangge_promoid",promolist_id);
			
			var idlist = promolist_id;
			var idArray = [];
			var id = getCookie('tiangge_id');
			var ids = id.split(".");
			var i = 0;					
			jQuery.each(ids , function(index, value){
				if (i==1) value=idlist;
				idArray.push(value);
				i++;
			});
									 
			id = idArray.join(".");
			setCookie("tiangge_id",id);
			//console.log(id);
				
			var price = jQuery("#choosePromo-inner .active").children('span').attr('class');
			var gadgetplanprice = getCookie('tiangge_planprice');
			//gadgetplanprice = gadgetplanprice.substr(1, gadgetplanprice.length-3);
			//gadgetplanprice = gadgetplanprice.replace(",", "");
			//console.log(price);
			//promolist_id = '3';
			//var gadgetplanprice = '3000.00';
			
			jQuery.getJSON(base_url+"getcommitmentperiod/"+promolist_id+"/"+gadgetplanprice,{ajax:'true'},function(j){
				j.sort(sort_by('period', true, parseInt));
				var ht = '';
				for(var i=0;i<j.length;i++){
				   //ht+='<a href="#." class="chooseCommited"><span class="coinIcons floatLeft"></span><p class="floatLeft rb">Total cash back: <b> P'+j[i].totalRebate+'0 </b>Cash back per registration:<b class="rba"> P'+j[i].rebateAmt+'0</b></p><h5 class="clear">'+j[i].period+' months</h5></a>';
				   ht+='<div class="chooseCommited"><div class="CRPCBdynamicUpper"><div class="CRPCBdynamicUpperIcon"></div><div class="CRPCBdynamicUpperText">Total cash back: <br> <b class="rb">P'+j[i].totalRebate+'0</b> <br> Cash back per registration: <br> <b class="rba">P'+j[i].rebateAmt+'0</b></div><div class="clear"></div></div><div class="CRPCBdynamicLower"><div class="CRPCBdynamicLowerText1">'+j[i].period+' months</div><div class="CRPCBdynamicLowerText2"></div></div></div>';
				}
				ht+='<div class="clear"></div>';
				jQuery("#commitment").show();
				jQuery("#commitment-inner").html(ht); 
				resizeIframe();
				if ("window", $( window ).width() < 361) {
					scrollFrameHeight('2100');
				} else  if ("window", $( window ).width() < 641) {
					scrollFrameHeight('2150');
				} else {
					scrollFrameHeight('900');
				}
			}); 
		}
	});
	
	/*Choose Rebate and Registration Period*/
	jQuery('#commitment-inner').on("click", ".chooseCommited", function () {
		var $this = $(this);
		$this.siblings().removeClass('active');
		jQuery(".CRPCBdynamicUpper, .CRPCBdynamicLowerText1, .CRPCBdynamicLowerText2").removeClass('active');
		if ($this.hasClass('active')) {
			$this.removeClass('active');
			jQuery(".CRPCBdynamicUpper, .CRPCBdynamicLowerText1, .CRPCBdynamicLowerText2", this).removeClass('active');
			jQuery("#promoConfirm").hide();
			jQuery(".commitmentBox").removeClass("active");
			jQuery("p#commitmentBox").html("None")
			resizeIframe();
			return false;
		} else {
			$this.addClass('active');
			jQuery(".CRPCBdynamicUpper, .CRPCBdynamicLowerText1, .CRPCBdynamicLowerText2", this).addClass('active');
			jQuery("#promoConfirm").show();
			jQuery(".commitmentBox").addClass("active");
			//resizeIframe();
			if ("window", $( window ).width() < 361) {
				scrollFrameHeight('2900');} 
			else  if ("window", $( window ).width() < 641) {
				scrollFrameHeight('2900');
			} else {
				scrollFrameHeight('1200');
			}
			var months=jQuery(".chooseCommited .CRPCBdynamicLowerText1.active").html();
			console.log("months: " + months);
			var totalrebate=jQuery(".CRPCBdynamicUpper.active .rb").html();
			console.log("totalrebate :" + totalrebate);
			var commitmentBox = months + ' - ' + totalrebate;
			setCookie("tiangge_commitmentBox",commitmentBox);
			setCookie("tiangge_commitmentMonths",months.replace(" months", ""));
			jQuery("#commitmentBox").text(months + ' - ' + totalrebate);
		
			// Summary 
			var choosePromo = jQuery(".choosePromo.active .choosePromodynamicLowerText1").html();
			var validity = jQuery("#validity-inner .selectValiditydynamicLower1.active").html();
			if (validity=="7 days") {
				var regval = "Must subscribe weekly throughout the registration period";
			} else if (validity=="15 days") {
				var regval = "Must subscribe twice a month throughout the registration period";
			} else {
				var regval = "Must subscribe monthly throughout the registration period";
			}
			rebateamt = jQuery(".CRPCBdynamicUpper.active .rba").text();
			console.log("rebateamt: " + rebateamt);
			rebateamt = rebateamt.replace(/\s/g, "");
			var price = jQuery("#choosePromo-inner .active").children('span').attr('class');
			price = format2(parseInt(price), "");
			//price = price.slice(0,-3);
			price = price.replace(/\s/g, "");
			console.log("price: " + price);
			
			setCookie("tiangge_choosePromo",choosePromo);
			var promoDesc = jQuery("#choosePromo-inner .active").children('span#promoDesc').text();
			promoDesc = ConvertFirstCharacterToUpperCase(promoDesc);
			jQuery("#summary-desc").text(promoDesc);
				
			setCookie("tiangge_validity",validity);
			setCookie("tiangge_months",months);
			setCookie("tiangge_totalrebate",totalrebate);
			setCookie("tiangge_rebateamt",rebateamt);
			setCookie("tiangge_promoprice",price);
			
			jQuery(".summary-promoname").text(choosePromo);
			jQuery("#summary-validity").text(validity);
			jQuery("#summary-regval").text(regval);  
			jQuery("#summary-months").text(months);
			totalrebate = totalrebate.replace("P", "");
			totalrebate = format2(parseInt(totalrebate), "");
			console.log("totalrebate: " + totalrebate);
			totalrebate = totalrebate.replace(/\s/g, "");
			jQuery(".summary-totalrebate").text(totalrebate);	
			jQuery("#summary-rebateamt").text(rebateamt);
			jQuery(".summary-promoprice").text(price);
			
			var gadgetprice = jQuery(".summary-gadgetprice").text();
			console.log("gadgetprice: " + gadgetprice);
			gadgetprice = gadgetprice.replace(",", "").substring(1);
			//console.log("gadgetprice: " + gadgetprice);
			
			var promoprice = jQuery(".summary-promoprice").text();
			promoprice = promoprice.replace(",", "");
			//console.log("promoprice - " + promoprice);
			var totalcash = parseInt(gadgetprice.replace(",", "")) + parseInt(promoprice);
			totalcash = format2(parseInt(totalcash), "P");
			//totalcash = totalcash.slice(0,-3);
			totalcash = totalcash.replace(/\s/g, "");
			jQuery(".summary-totalcash").text(totalcash);
			setCookie("tiangge_totalcash",totalcash);
			
			var totalrebate = jQuery(".summary-totalrebate").text();
			totalrebate = totalrebate.replace(",", "");
			var discounted = parseInt(gadgetprice.replace(",", "")) - parseInt(totalrebate);
			if(discounted<=0){
				jQuery("#summary-text1").text("With your cash back, the gadget price is now:");
			    jQuery("#summary-text2").html("Gadget Price<br/>(After Cash Back)");
				jQuery("#summary-free").css("display","block");
				jQuery(".summary-discounted").css("text-decoration","line-through");
				jQuery(".tdmodmtop").css("padding-top","5px");
			}
			else{
				jQuery("#summary-text1").text("With your cash back, the discounted gadget price is:");
			    jQuery("#summary-text2").html("Discounted <br/> Gadget <br/> Price");
				jQuery("#summary-free").css("display","none");
				jQuery(".summary-discounted").css("text-decoration","none");
			}
		
			discounted = format2(parseInt(discounted), "P");
			//discounted = discounted.slice(0,-3);
			discounted = discounted.replace(/\s/g, "");
			jQuery(".summary-discounted").text(discounted);	
			setCookie("tiangge_discounted",discounted);
			resizeIframe();
			//return false;
		}
	});
	
	/*Process Button*/
	jQuery("#btn_ProceedOrder").click(function(){
	    if (current_pos < 2) {
			setCookie("tiangge_current_pos","2");
		}
	});
	
	
    if(/promo/.test(self.location.href)){
	   var mode = getCookie("tiangge_mode");
	   var promo = getCookieR("tiangge_promo");
	   var promoDesc = getCookieR("tiangge_promoDesc");
	   var commitmentBox = getCookieR("tiangge_commitmentBox");
	   var mobtel = getCookieR("tiangge_mobtel");
	   var username = getCookieR("tiangge_username");
	   var eadd = getCookieR("tiangge_eadd");
	   var bday = getCookieR("tiangge_bday");
       var address = getCookieR("tiangge_address");
	   var area = getCookieR("tiangge_area");
	   var town = getCookieR("tiangge_town");
	   var province = getCookieR("tiangge_province");
	   var postalcode = getCookieR("tiangge_postalcode");
       if(mode=="edit"){
		 jQuery(".promoBox").addClass("active");
		 if (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0) {
			promoDesc = promoDesc.replace("john", ",");
			promoDesc = promoDesc.replace("john ", ", ");
			jQuery('#promo').html(promo + promoDesc);
		 } else {
			jQuery('#promo').html(promo + promoDesc);
		 }
		 jQuery(".commitmentBox").addClass("active");
		 jQuery('#commitmentBox').text(commitmentBox);
		 jQuery(".prepaidBox").addClass("active");
		 //jQuery('#mobtel').text(mobtel);
	     if(mobtel=="0"){jQuery('#mobtel').text("None");} else {jQuery('#mobtel').text(mobtel);}
		 jQuery(".pnone").hide();
	     jQuery(".profileBox").addClass("active");
		 jQuery('#name').text(username);
		 jQuery('#email').text(eadd);
		 jQuery('#dob').text(bday);
		 
		 if(province=="Metro Manila") 
			var address = address + ', ' + area + ', ' + town + ', ' + province + ', ' + postalcode;
		 else
			var address = address + ', ' + town + ', ' + province + ', ' + postalcode;
			
		 jQuery('#add').text(address);
		 jQuery("#pname").show();
		 jQuery("#pemail").show();
		 jQuery("#pdob").show();
		 jQuery("#padd").show();
		 jQuery('#btn_ProceedOrder').text("Save");
       }
    }
});

   //Sort Array by Field Name
   var sort_by = function(field, reverse, primer){

   var key = primer ? 
       function(x) {return primer(x[field])} : 
       function(x) {return x[field]};

   reverse = [-1, 1][+!!reverse];

   return function (a, b) {
       return a = key(a), b = key(b), reverse * ((a > b) - (b > a));
     } 
   }
   
   //Format Price
   function format2(n, currency) {
    return currency + " " + n.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
   }
   
   //ConvertFirstCharacterToUpperCase
   function ConvertFirstCharacterToUpperCase(text) {
    return text.substr(0, 1).toUpperCase() + text.substr(1);    
   }
   
   //Create Cookie
   function setCookie(cname,cvalue) {
    var d = new Date();
    d.setTime(d.getTime() + (30*60*1000));
	
	ua_tab2ics = "IMM76D";
	_ua = navigator.userAgent;
	
	if(_ua.search(ua_tab2ics) > 0)
	    document.cookie = cname+"="+cvalue+"; path=/"; 
	else{
	
	var expiration = getCookie("tiangge_expiration");
	if(expiration=="")
		var expires = "expires=" + d.toUTCString();
	else{
		var e = new Date();
		e.setTime(parseInt(expiration) + (30*60*1000));
	    var expires = "expires=" + e.toUTCString();
	}
	
	//document.cookie = cname+"="+cvalue+"; path=/;"+expires;
	document.cookie = cname+"="+cvalue+"; path=/";
	}
   }
   
   //Retrieve Cookie
   function getCookie(cname) {
	var name = cname + "=";
	var ca = document.cookie.split(';');
	for(var i=0; i<ca.length; i++) 
	{
	var c = ca[i].replace(/\s/g, "");
	if (c.indexOf(name)==0) return c.substring(name.length,c.length);
	}
	return "";
   }
   
   //Retrieve Cookie with space
   function getCookieR(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
   }
   
	function populateValidity(promo_id) {
		var base_url = baseurl + "promo/";
		jQuery.getJSON(base_url+"getpromovaliditylist/"+promo_id,{ajax:'true'},function(j){
			j.sort(sort_by('validity', true, parseInt));
			var ht = '';
			for(var i=0;i<j.length;i++){
				if(j[i].validity=='1') day='day'; else day='days';
					ht+='<div class="selectValidity"><div class="selectValiditydynamicUpper"><div class="selectValidityUpperText">'+j[i].validity+'</div></div><div class="selectValiditydynamicLower"><div class="selectValiditydynamicLower1">'+j[i].validity+' '+day+'</div><div class="selectValiditydynamicLower2"></div></div></div>';
				}
				ht+='<div class="clear"></div>';
				jQuery("div#validity").show();
				jQuery("#validity-inner").html(ht);
				var current_pos = getCookie("tiangge_current_pos");
				if (current_pos > 1) {
					var validity = getCookie("tiangge_validity");
					validity = parseInt(validity);
					jQuery("div#validity-inner .selectValidityUpperText:contains("+validity+")").addClass("active");
					jQuery('#validity-inner .selectValidity').filter(function(){
						return $(this).has('.active').length > 0
					}).each(function(){
						jQuery(".selectValiditydynamicUpper, .selectValiditydynamicLower1, .selectValiditydynamicLower2", this).addClass('active');
						jQuery(this).addClass("active");
					});
				}
		});
	}
  
	function populatePromoDetails(promo_id,name,validity) {
		var base_url = baseurl + "promo/";
		jQuery.getJSON(base_url+"getpromolist/"+promo_id+"/"+name+"/"+validity,{ajax:'true'},function(j){
				j.sort(sort_by('promoPrice', true, parseInt));
				var ht = '';
				for(var i=0;i<j.length;i++){
				  if(j[i].promoTextDesc=="unli allnet texts" || j[i].promoTextDesc=="unlimited texts to all networks") { 
					var promoTextDesc = "Unli to all networks"; 
				  } else {
					var promoTextDesc = j[i].promoTextDesc;
					promoTextDesc = promoTextDesc.replace(" to Globe/TM", "");
				  }
				  if(j[i].promoCallDesc=="unli calls to Globe/TM") {
					var promoCallDesc = ConvertFirstCharacterToUpperCase(j[i].promoCallDesc);
				  } else {
					  var promoCallDesc = j[i].promoCallDesc;
					  if (/minutes/.test(promoCallDesc)) { promoCallDesc = promoCallDesc.replace(" of calls to Globe/TM", "") + "*"; }
					  if (/mins of calls to Globe/.test(promoCallDesc)){ promoCallDesc = promoCallDesc.replace("mins of calls to Globe/TM", "") + "minutes*"; }
					  if (/mins of Globe/.test(promoCallDesc)) { promoCallDesc = promoCallDesc.replace("mins of Globe/TM calls", "") + "minutes*"; }
					  if (/null/.test(promoCallDesc) || promoCallDesc==="") { /*promoCallDesc = "None";*/ promoCallDesc = "0 minutes"; }
				  }
				  var promoSurfDesc = j[i].promoSurfDesc;
				  var promoPrice = j[i].promoPrice;
				  promoSurfDesc = promoSurfDesc.replace(" data", "");
				  promoPrice = promoPrice + "0";
				  var promoDesc = j[i].promoDesc;
				   
				  //ht+='<a href="#." class="choosePromo"><span style="display:none;" class="'+j[i].promoPrice+'" id="promolistid" >'+j[i].promoId+'</span><span style="display:none;" id="promoDesc" >'+promoDesc+'</span><ul><li><span class="choosePromoIcon one"></span>'+promoTextDesc+'</li><li><span class="choosePromoIcon two"></span>'+promoCallDesc+'</li><li><span class="choosePromoIcon three"></span>'+promoSurfDesc+'</li><li><span class="choosePromoIcon four"></span>'+promoPrice+'</li></ul><h5 style="font-size: 18px;margin: 9px 0 0 -9px;">'+j[i].promoName+'</h5></a>';
				  ht+='<div class="choosePromo"><span style="display:none;" class="'+j[i].promoPrice+'" id="promolistid" >'+j[i].promoId+'</span><span style="display:none;" id="promoDesc" >'+promoDesc+'</span><div class="choosePromodynamicUpper"><div class="rowcont"><div class="rowcontlogo image1"></div><div class="rowconttext">'+promoTextDesc+'</div><div class="clear"></div></div><div class="rowcont"><div class="rowcontlogo image2"></div><div class="rowconttext">'+promoCallDesc+'</div><div class="clear"></div></div><div class="rowcont"><div class="rowcontlogo image3"></div><div class="rowconttext">'+promoSurfDesc+'</div><div class="clear"></div></div><div class="rowcont"><div class="rowcontlogo image4"></div><div class="rowconttext">P'+promoPrice+'</div><div class="clear"></div></div><div class="clear"></div></div><div class="choosePromodynamicLower"><div class="choosePromodynamicLowerText1">'+j[i].promoName+'</div><div class="choosePromodynamicLowerText2"></div></div></div>';
				}
				jQuery("#choosePromo").show();
				jQuery("#choosePromo-inner").html(ht); 
				var maxHeight = -1;
				jQuery('.choosePromodynamicUpper').each(function() {
				  maxHeight = maxHeight > jQuery(this).height() ? maxHeight : jQuery(this).height();
				});

				jQuery('.choosePromodynamicUpper').each(function() {
				  jQuery(this).height(maxHeight);
				});
				
				var current_pos = getCookie("tiangge_current_pos");
				if (current_pos > 1) {
					var promolistid = getCookie("tiangge_choosePromo");
					//console.log(promolistid);
					jQuery("div#choosePromo-inner .choosePromodynamicLowerText1:contains("+promolistid+")").addClass("active");
					
					jQuery('#choosePromo-inner .choosePromo').filter(function(){
						return $(this).has('.active').length > 0
					}).each(function(){
						jQuery(".choosePromodynamicUpper, .choosePromodynamicLowerText1, .choosePromodynamicLowerText2", this).addClass('active');
						jQuery(this).addClass("active");
					});
				}
				resizeIframe();
		
			
			}); 
	}
	

	function populateCommitmentPeriod(promoTypeid,price) {
		var base_url = baseurl + "promo/";
		jQuery.getJSON(base_url+"getcommitmentperiod/"+promoTypeid+"/"+price,{ajax:'true'},function(j){
				j.sort(sort_by('period', true, parseInt));
				var ht = '';
				for(var i=0;i<j.length;i++){
				   //ht+='<a href="#." class="chooseCommited"><span class="coinIcons floatLeft"></span><p class="floatLeft rb">Total savings: <b> P'+j[i].totalRebate+'0 </b>Savings per Registration:<b class="rba"> P'+j[i].rebateAmt+'0</b></p><h5 class="clear">'+j[i].period+' months</h5></a>';
				   ht+='<div class="chooseCommited"><div class="CRPCBdynamicUpper"><div class="CRPCBdynamicUpperIcon"></div><div class="CRPCBdynamicUpperText">Total cash back: <br> <b class="rb">P'+j[i].totalRebate+'0</b> <br> Cash back per registration: <br> <b class="rba">P'+j[i].rebateAmt+'0</b></div><div class="clear"></div></div><div class="CRPCBdynamicLower"><div class="CRPCBdynamicLowerText1">'+j[i].period+' months</div><div class="CRPCBdynamicLowerText2"></div></div></div>';
				}
				ht+='<div class="clear"></div>';
				jQuery("#commitment").show();
				jQuery("#commitment-inner").html(ht); 
				var current_pos = getCookie("tiangge_current_pos");
				if (current_pos > 1) {
					var months = getCookieR("tiangge_months");
					console.log("months: " + months);
					jQuery("#commitment-inner .chooseCommited .CRPCBdynamicLowerText1:contains("+months+")").addClass("active");
					jQuery('#commitment-inner .chooseCommited').filter(function(){
						return $(this).has('.active').length > 0
					}).each(function(){
						jQuery(".CRPCBdynamicUpper, .CRPCBdynamicLowerText1, .CRPCBdynamicLowerText2", this).addClass('active');
						jQuery(this).addClass("active");
					});
					var totalrebate=jQuery(".CRPCBdynamicUpper.active .rb").html();
					totalrebate = totalrebate.replace("P", "");
					totalrebate = format2(parseInt(totalrebate), "");
					totalrebate = totalrebate.replace(/\s/g, "");
					jQuery(".summary-totalrebate").text(totalrebate);
				}
				var gadgetprice = getCookieR("tiangge_price");
				gadgetprice = gadgetprice.replace(",", "").substring(1);
				console.log("gadgetprice: " + gadgetprice);	
			
				var promoprice = getCookieR("tiangge_promoprice");
				promoprice = promoprice.replace(",", "");
				console.log("promoprice: " + promoprice);
				var totalcash = parseInt(gadgetprice) + parseInt(promoprice);
				totalcash = format2(parseInt(totalcash), "P");
				//totalcash = totalcash.slice(0,-3);
				totalcash = totalcash.replace(/\s/g, "");
				console.log("totalcash: " + totalcash);	
				jQuery(".summary-totalcash").text(totalcash);
				setCookie("tiangge_totalcash",totalcash);
					
				var totalrebate=jQuery(".CRPCBdynamicUpper.active .rb").html();
				
				totalrebate = totalrebate.replace("P", "");
				totalrebate = totalrebate.replace(/\s/g, "");
				totalrebate = format2(parseInt(totalrebate), "");
				totalrebate = totalrebate.replace(",", "").substring(1);
				console.log("totalrebate: " + totalrebate);	
				
				var discounted = parseInt(gadgetprice) - parseInt(totalrebate);
				if(discounted<=0){
				    jQuery("#summary-text1").text("With your cash back, the gadget price is now:");
					jQuery("#summary-text2").html("Gadget Price<br/>(After Cash Back)");
					jQuery("#summary-free").css("display","block");
					jQuery(".summary-discounted").css("text-decoration","line-through");
					jQuery(".tdmodmtop").css("padding-top","5px");
				}
				else{
					jQuery("#summary-text1").text("With your cash back, the discounted gadget price is:");
					jQuery("#summary-text2").html("Discounted <br/> Gadget <br/> Price");
					jQuery("#summary-free").css("display","none");
					jQuery(".summary-discounted").css("text-decoration","none");
				}
				
			discounted = format2(parseInt(discounted), "P");
			discounted = discounted.replace(/\s/g, "");
			console.log("discounted: " + discounted);	
			jQuery(".summary-discounted").text(discounted);	
			setCookie("tiangge_discounted",discounted);
			jQuery("#promoConfirm").show();
			resizeIframe();
					
	    }); 
	}
	
	function showWidth( ele, w ) {
		//console.log("The width for the " + ele + " is " + w + "px.");
	}